import React, { Component } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';

import moment from 'moment';
import DropDownSource from '@xforceplus/dropdown-source';
import DataGroupFilter from '@xforceplus/data-filter';
import { LanguagePackage } from '@/utils/createContext';
import { Button, Badge, Select, Row, Col, Input, InputNumber, Form, DatePicker } from 'antd';
import { getLogisticsRequestParam, getToSendList, getParcel, getOrderParam, getCountWait, getCountParcel } from '../module/action';
//------------------------------------------------
// mapping
import { sortList } from './mapping.js';
//------------------------------------------------
import './opetation.scss';

const FormItem = Form.Item
const InputGroup = Input.Group;
const { RangePicker } = DatePicker
const Option = Select.Option


class Opetation extends Component {
  state = {
    dateTime: { first: '', second: '' },
    amountWithTaxScope: { first: "", second: "" },
    checkFlag: false,//seconed 效验，目前暂时不用
  }
  onChangeSelect = (value) => {//排序
    const { switchSearch, logisticsRequestParam, pageParam } = this.props
    this.props.getOrderParam({ orderNum: value })
    if (switchSearch) {
      this.props.getParcel({
        logisticsParcelRequestParam: logisticsRequestParam,
        orderParam: { orderNum: value },
        pageParam: pageParam,
      })
    } else {
      this.props.getToSendList({
        logisticsGoodsRequestParam: logisticsRequestParam,
        orderParam: { orderNum: value },
        pageParam: pageParam,
      })
    }
  }
  search = () => {//搜索
    this.props.form.validateFieldsAndScroll((err, values) => {
      // console.log(`value->`, values)
      if (!values || err) return
      const {
        waybillNo, senderName, senderTel, receiverName, receiverTel, senderTimeScope, amountFirst, amountSecond,//待寄送筛选条件
        batchNo, invoiceNo, bussinessNo, amountWithTax, paperDrewDateScope,//包裹筛选条件
      } = values
      const { switchSearch, orderParam, pageParam, logisticsRequestParam, status } = this.props
      const { dateTime, amountWithTaxScope } = this.state
      // console.log(`logisticsRequestParam------>`, logisticsRequestParam)
      const param = logisticsRequestParam
      if (switchSearch) {
        param.waybillNo = waybillNo ? waybillNo : ''
        param.senderName = senderName ? senderName : ""
        param.senderTel = senderTel ? senderTel : ""
        param.receiverName = receiverName ? receiverName : ""
        param.receiverTel = receiverTel ? receiverTel : ""
        param.senderTimeScope = dateTime ? dateTime : { first: "", second: "" }
        param.businessLgtStatus = status.businessLgtStatus,
          param.parcelFlag = status.parcelFlag,
          this.props.getLogisticsRequestParam(param)
        this.props.getParcel({
          logisticsParcelRequestParam: param,
          orderParam: orderParam,
          pageParam: pageParam,
        })
        this.props.getCountParcel(param)
      } else {
        param.batchNo = batchNo ? batchNo : ""
        param.invoiceNo = invoiceNo ? invoiceNo : ""
        param.bussinessNo = bussinessNo ? bussinessNo : ""
        param.paperDrewDateScope = dateTime ? dateTime : { first: "", second: "" }
        param.createTimeScope = { first: "", second: "" }
        param.amountWithTaxScope = amountWithTaxScope ? amountWithTaxScope : { first: "", second: "" }
        this.props.getLogisticsRequestParam(param)
        // console.log(`param======>`, param, `orderParam======>`, orderParam, 'pageParam===>', pageParam)
        this.props.getToSendList({
          logisticsGoodsRequestParam: param,
          orderParam: orderParam,
          pageParam: pageParam,
        })
        this.props.getCountWait(param)
      }
    })
  }

  amountChange = (value, type) => {
    const { amountWithTaxScope, checkFlag } = this.state
    const { validateFields } = this.props.form
    this.setState({
      amountWithTaxScope: {
        first: type === 'first' ? value : amountWithTaxScope.first,
        second: type === 'second' ? value : amountWithTaxScope.second,
      },
      checkFlag: type === 'second' ? true : false,//second 效验
    })
    if (type === 'second') {
      if (value < amountWithTaxScope.first) {
        validateFields(['amountSecond'], { force: checkFlag })
      }
    }
  }

  reset = () => {
    const { setFields } = this.props.form;
    const { switchSearch, orderParam, pageParam, logisticsRequestParam } = this.props
    this.setState({
      dateTime: { first: '', second: '' },
      amountWithTaxScope: { first: "", second: "" },
    })
    setFields({
      "batchNo": "",
      "invoiceNo": "",
      "bussinessNo": "",
      "paperDrewDateScope": "",
      "amountFirst": "",
      "amountSecond": "",
      "amountWithTax": "",
      "waybillNo": "",
      "senderName": "",
      "senderTel": "",
      "senderTimeScope": "",
      "receiverName": "",
      "receiverTel": ""
    })
    // if (switchSearch) {//------------需求变动，点击重置的时候 显示所有列表，直接取消这段注释就行
    //   this.props.getParcel({
    //     logisticsParcelRequestParam: logisticsRequestParam,
    //     orderParam: orderParam,
    //     pageParam: pageParam,
    //   })
    //   this.props.getCountParcel(logisticsRequestParam)
    // } else {
    //   this.props.getToSendList({
    //     logisticsGoodsRequestParam: logisticsRequestParam,
    //     orderParam: orderParam,
    //     pageParam: pageParam,
    //   })
    //   this.props.getCountWait(logisticsRequestParam)
    // }
    this.props.getLogisticsRequestParam()
  }

  dataOnChange = (dates, dateStrings) => {// 选择时间
    this.setState({
      dateTime: {
        first: dateStrings[0],
        second: dateStrings[1]
      }
    })
  }

  render() {
    const { getFieldDecorator, validateFieldsAndScroll } = this.props.form;
    const { switchSearch, orderParam, logisticsRequestParam } = this.props;
    const { amountWithTaxScope, checkFlag } = this.state
    const filterWaitSend = <React.Fragment>
      <FormItem label='批次封面'>
        {getFieldDecorator(`batchNo`, {
          rules: [{ required: false, message: 'Input something!' }],
        })(
          <Input placeholder="批次封面" />
        )}
      </FormItem>
      <FormItem label='价税合计'>
        <InputGroup compact>
          {getFieldDecorator(`amountFirst`, {
            rules: [{ required: false, message: 'Input something!' }],
          })(<InputNumber
            style={{ width: 160 }}
            placeholder="合计金额"
            onChange={(value) => this.amountChange(value, 'first')}
            min={0}
            formatter={value => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
            parser={value => value.replace(/\$\s?|(,*)/g, '')} />)}
          <Input style={{ width: 30, borderLeft: 0, pointerEvents: 'none', backgroundColor: '#fff' }} placeholder="-" disabled />
          {getFieldDecorator(`amountSecond`, {
            rules: [{ required: false, message: 'Input something!' }],
          })(<InputNumber
            style={{ width: 160, borderLeft: 0 }}
            placeholder="合计金额"
            onChange={(value) => this.amountChange(value, 'second')}
            min={amountWithTaxScope.first ? amountWithTaxScope.first : 0}
            formatter={value => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
            parser={value => value.replace(/\$\s?|(,*)/g, '')}
          />)}
        </InputGroup>
      </FormItem>
      <FormItem label='业务单号'>
        {getFieldDecorator(`bussinessNo`, {
          rules: [{ required: false, message: 'Input something!' }],
        })(<Input placeholder="业务单号" />
        )}
      </FormItem>
      <FormItem label='发票号码'>
        {getFieldDecorator(`invoiceNo`, {
          rules: [{ required: false, message: 'Input something!' }],
        })(<Input placeholder="发票号码" />
        )}
      </FormItem>
      <FormItem label="开票日期">
        {getFieldDecorator('paperDrewDateScope')(
          <RangePicker
            ranges={{ Today: [moment(), moment()], 'This Month': [moment(), moment().endOf('month')] }}
            showTime
            format="YYYY-MM-DD hh:mm:ss"
            onChange={this.dataOnChange}
          />
        )}
      </FormItem>
    </React.Fragment>
    const filterCountParcel = <React.Fragment>
      <FormItem label='寄件方'>
        {getFieldDecorator(`senderName`, {
          rules: [{ required: false, message: 'Input something!' }],
        })(<Input placeholder="寄件方" />
        )}
      </FormItem>
      <FormItem label='寄件方电话'>
        {getFieldDecorator(`senderTel`, {
          rules: [{ required: false, message: 'Input something!' }],
        })(<Input placeholder="寄件方电话" />
        )}
      </FormItem>
      <FormItem label="发件日期">
        {getFieldDecorator('senderTimeScope')(
          <RangePicker
            ranges={{ Today: [moment(), moment()], 'This Month': [moment(), moment().endOf('month')] }}
            showTime
            format="YYYY-MM-DD hh:mm:ss"
            onChange={this.dataOnChange}
          />
        )}
      </FormItem>
      <FormItem label='收件方'>
        {getFieldDecorator(`receiverName`, {
          rules: [{ required: false, message: 'Input something!' }],
        })(<Input placeholder="收件方" />
        )}
      </FormItem>
      <FormItem label='收件方电话'>
        {getFieldDecorator(`receiverTel`, {
          rules: [{ required: false, message: 'Input something!' }],
        })(<Input placeholder="收件方电话" />
        )}
      </FormItem>
      <FormItem label='快递单号'>
        {getFieldDecorator(`waybillNo`, {
          rules: [{ required: false, message: 'Input something!' }],
        })(<Input placeholder="快递单号" />
        )}
      </FormItem>
    </React.Fragment>

    return (
      <React.Fragment>
        <Row type="flex" justify="space-between" className="optation-box">
          <Col span={19}>
            <Form layout="inline">
              {switchSearch ? filterCountParcel : filterWaitSend}
              <FormItem>
                <Button type="primary" onClick={this.search}>查询</Button>
                <Button onClick={this.reset} style={{ marginLeft: '8px' }}>重置</Button>
              </FormItem>
            </Form>
          </Col>
          <Col>
            <Select
              defaultValue={2}//默认创建时间降序
              onChange={this.onChangeSelect}
              style={{ width: '160px' }}
              placeholder="请选择排序方式">
              {switchSearch ? sortList.parcel.map(item => {
                return (
                  <Option key={item.id} value={item.id}>{item.label}</Option>
                );
              }) : sortList.waitSend.map(item => {
                return (
                  <Option key={item.id} value={item.id}>{item.label}</Option>
                );
              })}

            </Select>
          </Col>
        </Row>
      </React.Fragment>
    );
  }
};

function mapStateToProps(state) {
  const {
    orderParam,// 排序方式
    switchSearch,//筛选switch
    logisticsRequestParam,//筛选器对象  
  } = state.logistics;
  return {
    orderParam,// 排序方式
    switchSearch,//筛选switch
    logisticsRequestParam,//筛选器对象  
  };
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators({
    getCountWait,//待寄送统计
    getCountParcel,//包裹统计
    getLogisticsRequestParam,//筛选条件
    getToSendList,//待寄送列表
    getParcel, // 获取包裹数
    getOrderParam,//排序方式
  }, dispatch);
}

export default connect(mapStateToProps, mapDispatchToProps)(Form.create()(Opetation));
